<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 style="text-align: center;">登录</h2>
      <el-form :model="form" @submit.prevent="onLogin" :rules="rules" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%;"
            @click="onLogin"
            :loading="loading"
            :disabled="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const formRef = ref(null) 
const form = reactive({
  username: '',
  password: ''
})
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

async function onLogin() {
  try {
    await formRef.value.validate()
  } catch (validateErr) {
    return
  }

  loading.value = true
  try {
    const resp = await axios.post('/authentic/login', {
      username: form.username.trim(),
      password: form.password
    })

    const data = resp?.data ?? resp

    if (data && data.code === 200) {
      const token = data.data?.token ?? data.data
      if (token) {
        localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      }
      ElMessage.success(data.message || '登录成功')
      router.replace('/main')
    } else {
      ElMessage.error((data && data.message) || '登录失败')
    }
  } catch (err) {
    const msg = err?.response?.data?.message || err?.message || '网络错误，请重试'
    ElMessage.error(msg)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f6f8fc;
}
.login-card {
  width: 350px;
  padding: 20px 10px;
}
</style>
